use std::path::Path;

use clap::{Arg, ArgMatches, Command};

use crate::environment::environment;
use crate::index::index;
use crate::runtime::runtime::path;
use crate::util::util::system;
use crate::util::util::system::syscall;

pub const NAME: &'static str = "rem";

pub fn new() -> Command {
    let mut command = Command::new(NAME).about("工具包移除命令，用于处理工具包移除及环境清理的任务");
    command = command.arg(Arg::new("name").required(true).help("工具名称"));
    command = command.arg(Arg::new("version").required(true).help("工具版本"));

    command
}

pub fn action(args: &ArgMatches) {
    let name = args.get_one::<String>("name").unwrap();
    let version_name = args.get_one::<String>("version").unwrap();

    if !environment::is_installed(name, version_name) {
        return;
    }

    let software = index::index().get(name);
    if software.is_none() {
        println!("未知的工具名称: {}", name);

        return;
    }

    let software = software.unwrap();
    let version = software.get_version(version_name);
    if version.is_none() {
        println!("工具[{}]未找到版本[{}]配置，请更新本地索引或反馈此问题", name, version_name);

        return;
    }

    let path = Path::new(path::DEM_SOFTWARE_PATH).join(name).join(version_name);

    let version = version.unwrap();
    if version.archive.enable && 0 != version.archive.script.remove.before.len() {
        for script in version.archive.script.remove.before.iter() {
            let script = path::replace_package_tokens(script, path.to_str().unwrap(), version.version.as_str(), None);
            let result = syscall::execute_system_command(script.as_str(), Some(path.to_str().unwrap()), None);
            if result.is_err() {
                println!("执行移除前脚本失败: {} {}", script, result.unwrap_err());
            }
        }
    }

    let result = system::fs::remove_dir_all(path.to_str().unwrap());
    if result.is_err() {
        println!("移除工具[{}]的版本[{}]失败，失败原因: {}", name, version_name, result.unwrap_err());

        return;
    }

    if version.archive.enable && 0 != version.archive.script.remove.after.len() {
        for script in version.archive.script.remove.after.iter() {
            let script = path::replace_package_tokens(script, path.to_str().unwrap(), version.version.as_str(), None);
            let result = syscall::execute_system_command(script.as_str(), Some(path.to_str().unwrap()), None);
            if result.is_err() {
                println!("执行清理脚本失败: {} {}", script, result.unwrap_err());
            }
        }
    }

    println!("移除完成");
}